package com.gin.kotlin.no_gay_alliance.adapter.pm

import android.content.Context
import android.content.DialogInterface
import android.view.View
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.base.AbstractBindingRecyclerViewAdapter
import com.gin.kotlin.no_gay_alliance.base.AlertDialogUtils
import com.gin.kotlin.no_gay_alliance.base.GlideModule.Companion.CROSS_FADE
import com.gin.kotlin.no_gay_alliance.base.MyHandler
import com.gin.kotlin.no_gay_alliance.base.TextViewTarget
import com.gin.kotlin.no_gay_alliance.databinding.ItemPrivateMessageUserBinding
import com.gin.nga.callback.NgaCallback
import com.gin.nga.response.base.NgaResponse
import com.gin.nga.response.user.SimpleUserInfo
import retrofit2.Call
import retrofit2.Response

class PrivateMessageBlackListAdapter(context: Context, handler: MyHandler) :
    AbstractBindingRecyclerViewAdapter<ItemPrivateMessageUserBinding, SimpleUserInfo>(context, handler, false),
    View.OnClickListener, NgaCallback<List<String>> {
    override fun onBindViewHolder(holder: ViewHolder<ItemPrivateMessageUserBinding>, position: Int, b: ItemPrivateMessageUserBinding, dataModel: SimpleUserInfo) {
        b.ivPmBlockAdd.visibility = View.GONE

        b.tvUsername.text = dataModel.username

        // 图标大小（dp）
        val size = (32 * context.resources.displayMetrics.density).toInt()

        Glide.with(context)
            .load(dataModel.getAvatars()?.get(0))
            .apply(RequestOptions().circleCrop())
            .error(R.drawable.ic_person_18)
            .transition(DrawableTransitionOptions.withCrossFade(CROSS_FADE))
            .into(TextViewTarget(b.tvUsername, 0, size, size))

        b.ivDelete.tag = dataModel
        b.ivDelete.setOnClickListener(this)

    }

    override fun onClick(v: View?) {
        val dataModel = v?.tag as? SimpleUserInfo ?: return
        AlertDialogUtils.builder(context, "将 ${dataModel.username} 从黑名单移除", listener = { _, which ->
            if (which == DialogInterface.BUTTON_POSITIVE) App.INSTANCE.ngaApi.messageApi.blockDel(dataModel.userId!!).enqueue(this)
        }).show()
    }

    override fun onSuccess(call: Call<NgaResponse<List<String>>>, response: Response<NgaResponse<List<String>>>, body: NgaResponse<List<String>>?, data: List<String>?) {
        data?.get(0)?.also { handler.toast(it) }
    }

    override fun onError(call: Call<NgaResponse<List<String>>>, response: Response<NgaResponse<List<String>>>, body: NgaResponse<List<String>>?, errorMessage: String) {
        handler.toastLong(errorMessage)
    }
}